package db

import (
	"duanju-mq/pkg/app"
	"duanju-mq/pkg/config"
	"duanju-mq/pkg/mysql"
	"duanju-mq/pkg/redis"
)

var (
	fDBAddr    = config.String("api.mysql.addr", "127.0.0.1:3306", "mysql addr")
	fLogDBName = config.String("api.mysql.name", "", "mysql db admin name")
	fDBUser    = config.String("api.mysql.user", "", "mysql db user")
	fDBPwd     = config.String("api.mysql.pwd", "", "mysql db password")

	fSysRedisAddr   = config.String("sys.redis.addr", "127.0.0.1:6379", "redis addr")
	fSysRedisPwd    = config.String("sys.redis.pwd", "", "redis password")
	fSysRedisPrefix = config.String("sys.redis.prefix", "duanju/sys/", "redis prefix")

	mqDB     *mysql.DB
	sysRedis *redis.Client

	dbInits = []func(){}
)

func init() {
	app.OnStart(func() {
		mysql.SetDefaultConnPool(30)
		mqDB, _ = mysql.Open(*fDBAddr, *fDBUser, *fDBPwd, *fLogDBName)

		sysRedis = redis.Connect(&redis.Server{
			Prefix: *fSysRedisPrefix,
			Addr:   *fSysRedisAddr,
			Pwd:    *fSysRedisPwd,
		})

		for _, fn := range dbInits {
			fn()
		}

	})
}

func AfterDbOpen(fn func()) {
	dbInits = append(dbInits, fn)
}

func MqDB() *mysql.DB {
	return mqDB
}

func SysRedis() *redis.Client {
	return sysRedis
}
